#!/usr/bin/env python
'''
Created on Sep 13, 2009
@author: yanghoch
'''
import sys
import os
import getopt
'''
This program translates the exons format into junctions
'''

def exons2JunctionsBed( exonsFileN, junctionBedFileN ):
    ''' Given an Genome browswer output file with the following cols  
    (1)gene (2)chr (3)strand (3)exons' starts (4)exons' end (comma sep)
    , with exons of a gene in each line, output the splicing junctions
    in bed file, with each line a junction. 
    '''
    def outputJunctionsBedLine( ofile, exonsStarts, exonsEnds, geneInfo ):
        noExonsS = len( exonsStarts )
        noExonsE = len( exonsEnds )
        if( noExonsS == noExonsE ):
            noIntron = len( exonsStarts ) - 1
            for i in range( noIntron ):
                junction = [exonsEnds[i], exonsStarts[i + 1]]
                gene = geneInfo[0]
                chrN = geneInfo[1]
                strand = geneInfo[2]
                ofile.write( chrN + '\t'\
                            + junction[0] + '\t'\
                            + junction[1] + '\t'\
                            + gene + '\t1\t' + strand + '\n' )

    exonsFile = open( exonsFileN, 'r' )
    junctionBedFile = open( junctionBedFileN, 'w' )
    # line = exonsFile.readline() # the header
    for line in exonsFile.readlines():
        geneInfo = line.split( "\t" )
        NoOfColInExonFormat = 5
        if len( geneInfo ) == NoOfColInExonFormat:
            exonsStarts = geneInfo[3].split( ',' )
            exonsEnds = geneInfo[4].split( ',' )
            noExons = len( exonsStarts )
            # at least two exons will have one intron.
            if( noExons > 1 ):
                outputJunctionsBedLine\
                    ( junctionBedFile, exonsStarts, exonsEnds, geneInfo )
    exonsFile.close();
    junctionBedFile.close();

def usage():
    sys.stderr.write( "Working dir is " + os.getcwd() + '\n' )
    print __doc__
    print "argv[1] is the exons info from UCSC genome browser."
    print "argv[2] is output file, providing junction info in bed format."

def main():
    try:
        opts, args = getopt.getopt( sys.argv[1:], 'h', ["help"] )
    except getopt.error, msg:
        print msg
        sys.exit( 2 );
    #process options and argument 
    for o in opts:
        if o in ( "-h", "--help" ):
            print __doc__
            sys.exit();

    if( len( args ) == 2 ):
        exons2JunctionsBed( args[0], args[1] );
    else:
        usage();

if __name__ == '__main__':
    main()
